package com.example.softbank;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 读取输入流数据并转换为字符串
 *
 * @author likai
 * @version 20210120
 */
public class ReadInputSteamUtil {

	public static String parse(InputStream in, String charSetName) throws IOException {
		if (charSetName == null || "".equals(charSetName)) {
			charSetName = "UTF-8";
		}
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
		BufferedInputStream bufferIn = new BufferedInputStream(in);
		byte[] buf = new byte[1024];
		int len;
		byte[] lenBytes = new byte[6];
		bufferIn.read(lenBytes);
		Integer dataLen = Integer.valueOf(new String(lenBytes));
		while ((len = bufferIn.read(buf)) != -1) {
			byteArrayOutputStream.write(buf, 0, len);
			dataLen = dataLen - len;
			if (dataLen <= 0) {
				break;
			}
		}
		return new String(byteArrayOutputStream.toByteArray(), charSetName);
	}
}
